package com.carl.zeus.web.system;

import com.alibaba.fastjson.JSON;
import com.carl.zeus.common.annotation.Log;
import com.carl.zeus.common.constant.BusinessCode;
import com.carl.zeus.common.constant.BusinessMsg;
import com.carl.zeus.common.util.BusinessMsgUtil;
import com.carl.zeus.model.system.SysDepartment;
import com.carl.zeus.model.system.SysRole;
import com.carl.zeus.server.system.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 部门管理Controller
 * 
 * @author 作者: zcm
 * @date 创建时间：2017年3月8日 下午1:32:02
 */
@Controller
@RequestMapping(value="sys/dept")
public class DeptController {
	
	@Autowired
	private SysDeptService sysDeptService;
	
	//列表页面
	@Log("部门列表")
	@RequestMapping(value="list", method = RequestMethod.GET)
	public String list() {
		return "system/dept";
	}
	
	//获取角色分页对象
	@RequestMapping(value="listAjax", method = RequestMethod.GET)
	@ResponseBody
	public String listAjax(@RequestParam(value = "page", defaultValue = "1") int page,
							  @RequestParam(value = "limit", defaultValue = "10") int limit) {
		Map<String, Object> map = new HashMap<>();
		List<SysDepartment> userList = sysDeptService.listAjax(page, limit);
		map.put("code",0);
		map.put("msg","");
		map.put("count", sysDeptService.countMenuList());
		map.put("data", userList);
		return JSON.toJSONString(map);
	}
	
	//编辑页面
	@Log("编辑部门")
	@RequestMapping(value="edit/{id}")
	public String edit(@PathVariable("id") Long id,Model model) {
		if(id != null){
			SysDepartment dept = sysDeptService.selectById(id);
			model.addAttribute("dept", dept);
		}
		return "system/dept-edit";
	}


	/**
	 * 失效
	 * @return
	 */
	@Log("失效部门")
	@RequestMapping("/fail")
	@ResponseBody
	public BusinessMsg fail(@RequestParam("roleId") Long roleId){
		try {
			return sysDeptService.updateDeptStatus(roleId);
		} catch (Exception e) {
			return BusinessMsgUtil.returnCodeMessage(BusinessCode.ROLE_FAILK_ERROR);
		}
	}

	/**
	 * 批量失效
	 * @param deptIds 部门ids
	 * @return
	 */
	@Log("批量失效部门")
	@RequestMapping("/batchFail")
	@ResponseBody
	public BusinessMsg batchFail(@RequestParam(value = "deptIds[]") Long[] deptIds){
		try {
			return sysDeptService.updateDeptBatchStatus(deptIds);
		} catch (Exception e) {
			return BusinessMsgUtil.returnCodeMessage(BusinessCode.ROLE_FAILK_ERROR);
		}
	}

	// 增加和修改
	@Log("保存部门")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BusinessMsg save(SysDepartment department) {
		department.setUpdateTime(new Date());
		if (StringUtils.isNotEmpty(department.getName()) && department.getCreateTime() == null) {
			department.setCreateTime(new Date());
			sysDeptService.insertOrUpdate(department);
		}
		return BusinessMsgUtil.returnCodeMessage(BusinessCode.GLOBAL_SUCCESS);
	}
}
